<template>
  <div class="app-container">
    <div class="top_search_form">
      <el-form
        :model="formInfo"
        ref="formInfoRef"
        inline
        :label-width="appStore.language == 'zh' ? '100px' : '150px'"
      >
        <el-form-item :label="t('summary.summaryType')">
          <el-select
            v-model="formInfo.SummaryType"
            :placeholder="t('summary.summaryTypePlaceholder')"
            style="width: 160px"
          >
            <el-option
              v-for="item in summaryTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="t('assetsList.assetType')">
          <el-select
            v-model="formInfo.assetsClassifyId"
            :placeholder="t('assetsList.assetTypePlaceholder')"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in AssetClassification"
              :key="item.dictionaryKey"
              :label="item.dictionaryName"
              :value="item.dictionaryCode"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="t('summary.organization')">
          <el-tree-select
            style="width: 180px"
            clearable
            v-model="formInfo.organizationId"
            :placeholder="t('summary.organizationPlaceholder')"
            :data="depts"
            :props="{ label: 'Label', children: 'children', value: 'value' }"
            check-strictly
            :highlight-current="true"
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="queryList">{{
            t("common.search")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_container">
      <div class="table_top_btn">
        <right-toolbar
          ref="rightToolRef"
          @queryTable="queryList"
          :columns="diymicColums"
          :advanceVisible="false"
        >
        </right-toolbar>
      </div>
      <div class="table_area">
        <el-table
          ref="assetsTableRef"
          height="100%"
          v-loading="loading"
          :data="assetsData"
          :header-cell-style="{ textAlign: 'center' }"
          :summary-method="getSummaries"
          show-summary
          :cell-style="{ textAlign: 'center' }"
        >
          <template v-for="(item, index) in diymicColums" :key="item.key">
            <el-table-column
              v-if="item.visible"
              :prop="item.prop"
              :label="item.label"
              :width="item.width"
              :show-overflow-tooltip="true"
            >
              <template #default="{ row }">
                <span
                  v-if="[item.prop] == t('summary.subtotal')"
                  :style="{ color: colors.primaryColor }"
                >
                  {{ row[item.prop] || "0" }}
                </span>
                <span v-else>{{ row[item.prop] || "0" }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup name="AssetisList">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import useAppStore from "@/store/modules/app";
const appStore = useAppStore();
import colors from "@/assets/styles/variables.module.scss";
import {
  GetAssetStatisticsList,
  GetAssetSummary,
} from "@/api/statisticalManagement/index";
import { GetOrganizationTreeAll } from "@/api/assetsManage/organization";
import RightToolbar from "@/components/RightToolbar";
import { getUserInfo } from "@/utils/auth";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
const { AssetClassification } = proxy.useDict("AssetClassification");

const assetsData = ref([]); //资产列表数据
const loading = ref(false);
const diymicColums = ref([]); //动态表头

const formInfo = ref({
  assetsClassifyId: "",
  organizationId: "",
  SummaryType: 0,
});

const summaryTypes = [
  { label: "类型/所属组织", value: 0 },
  { label: "类型/使用组织", value: 1 },
  { label: "所属组织/类型", value: 2 },
  { label: "所属组织/使用组织", value: 3 },
  { label: "使用组织/类型", value: 4 },
  { label: "使用组织/所属组织", value: 5 },
];

const depts = ref([]); // 组织树数据

import { h } from "vue";

const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h(
        "div",
        {
          style: {
            textDecoration: "underline",
            textAlign: "center",
            color: colors.primaryColor,
          },
        },
        [`${t("summary.total")}`]
      );
      return;
    }

    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      const total = values.reduce((prev, curr) => {
        const value = Number(curr);
        return !Number.isNaN(value) ? prev + value : prev;
      }, 0);

      sums[index] = h(
        "div",
        {
          style: {
            textAlign: "center",
            color: colors.primaryColor,
          },
        },
        [total.toString()]
      );
    } else {
      sums[index] = h(
        "div",
        {
          style: {
            textAlign: "center",
            color: "#1065ff",
            color: "#ccc",
          },
        },
        ["N/A"]
      );
    }
  });

  return sums;
};

const queryOrganization = () => {
  GetOrganizationTreeAll("")
    .then((res) => {
      depts.value = res.output;
    })
    .catch((err) => {
      console.log("组织获取失败", err);
    });
};

const queryList = () => {
  const rawForm = { ...formInfo.value };
  const params = {
    ...rawForm,
    assetsClassifyId: rawForm.assetsClassifyId || "-1",
    // ownershipOrganizationalId: rawForm.ownershipOrganizationalId || '-1',
    // useOrganizationId: rawForm.useOrganizationId || '-1',
    organizationId: rawForm.organizationId,
  };
  console.log("查询参数1", params);
  loading.value = true;
  GetAssetSummary(params)
    .then((res) => {
      loading.value = false;
      assetsData.value = res.output;

      diymicColums.value = generateTableColumns(assetsData.value, [], {
        visible: true,
        width: "auto",
        isclick: false,
      });
    })
    .catch((err) => {
      loading.value = false;
    });
};

const generateTableColumns = (data, fixedColumns = [], options = { visible: true }) => {
  if (!Array.isArray(data) || data.length === 0) return fixedColumns;

  const keys = Object.keys(data[0]);
  const dynamicCols = keys.map((key, index) => ({
    key: index + fixedColumns.length,
    label: key,
    prop: key,
    visible: options.visible !== false, // 根据 options 设置可见性
    ...options,
  }));

  // 添加“横向合计”列
  dynamicCols.push({
    key: dynamicCols.length + fixedColumns.length,
    label: `${t("summary.subtotal")}`,
    prop: `${t("summary.subtotal")}`,
    visible: true, // 确保“横向合计”列总是显示
    ...options,
  });

  return [...fixedColumns, ...dynamicCols];
};

watch(
  () => diymicColums.value, // 监听列的变化
  () => {
    // 每当列的可见性发生变化时，重新计算每一行的横向合计
    assetsData.value.forEach((row) => {
      row[`${t("summary.subtotal")}`] = 0;
      // 只计算 visible 为 true 的列
      row[`${t("summary.subtotal")}`] = diymicColums.value
        .filter((col) => col.visible) // 只保留 visible 为 true 的列
        .reduce((acc, col) => {
          const value = Number(row[col.prop]); // 获取列值
          return acc + (isNaN(value) ? 0 : value); // 加总数值
        }, 0); // 初始值为 0
    });
  },
  { deep: true } // 深度监听，确保在嵌套的对象变化时也能触发
);

onMounted(() => {
  queryList();
  queryOrganization();
});
</script>
<style lang="scss" scoped>
.top_search_form {
  background-color: #fff;
  margin-bottom: 20px;
  padding: 20px 0px 0 0px;
  border-radius: 6px;
  display: flex;
  // align-items: center;
  max-height: 70px;
  overflow-y: auto;
}

.table_container {
  height: calc(100% - 100px);
}
</style>
